package com.kika.obwiki.controller;

import com.kika.obwiki.resp.CommonResp;
import com.kika.obwiki.service.NotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * WebSocket测试控制器
 * 用于测试WebSocket通知功能
 */
@RestController
@RequestMapping("/websocket")
public class WebSocketController {

  private static final Logger LOG = LoggerFactory.getLogger(WebSocketController.class);

  @Autowired
  private NotificationService notificationService;

  /**
   * 发送测试通知
   * 
   * @param message 通知消息
   * @return 响应结果
   */
  @PostMapping("/send-test")
  public CommonResp sendTestNotification(@RequestParam String message) {
    CommonResp resp = new CommonResp<>(true, "通知发送成功", null);

    try {
      notificationService.sendGlobalNotification(message);
      LOG.info("发送测试通知：{}", message);
    } catch (Exception e) {
      LOG.error("发送通知失败", e);
      resp.setSuccess(false);
      resp.setMessage("通知发送失败：" + e.getMessage());
    }

    return resp;
  }

  /**
   * 发送指定用户通知
   * 
   * @param userId  用户ID
   * @param message 通知消息
   * @return 响应结果
   */
  @PostMapping("/send-user")
  public CommonResp sendUserNotification(@RequestParam String userId, @RequestParam String message) {
    CommonResp resp = new CommonResp<>(true, "通知发送成功", null);

    try {
      notificationService.sendSystemNotification(message, userId);
      LOG.info("发送用户通知：{} -> {}", userId, message);
    } catch (Exception e) {
      LOG.error("发送用户通知失败", e);
      resp.setSuccess(false);
      resp.setMessage("通知发送失败：" + e.getMessage());
    }

    return resp;
  }

  /**
   * 获取在线用户数
   * 
   * @return 在线用户数
   */
  @GetMapping("/online-count")
  public CommonResp getOnlineCount() {
    CommonResp resp = new CommonResp<>(true, "查询成功", null);

    try {
      int count = notificationService.getOnlineUserCount();
      resp.setContent(count);
      LOG.info("当前在线用户数：{}", count);
    } catch (Exception e) {
      LOG.error("查询在线用户数失败", e);
      resp.setSuccess(false);
      resp.setMessage("查询失败：" + e.getMessage());
    }

    return resp;
  }

  /**
   * 检查用户是否在线
   * 
   * @param userId 用户ID
   * @return 是否在线
   */
  @GetMapping("/check-online")
  public CommonResp checkUserOnline(@RequestParam String userId) {
    CommonResp resp = new CommonResp<>(true, "查询成功", null);

    try {
      boolean isOnline = notificationService.isUserOnline(userId);
      resp.setContent(isOnline);
      LOG.info("用户{}在线状态：{}", userId, isOnline);
    } catch (Exception e) {
      LOG.error("检查用户在线状态失败", e);
      resp.setSuccess(false);
      resp.setMessage("查询失败：" + e.getMessage());
    }

    return resp;
  }
}